package com.orion.util;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Map;

/**
 * @author Administrator
 * @date 2021/11/11
 */
public class JwtUtil {

    private static Key getKeyInstance(String salt) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        String apiKey = DatatypeConverter.printBase64Binary(salt.getBytes());
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey);
        return new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
    }

    public static String createToken(Map<String, Object> claims, String salt) {
        claims.put("time",System.currentTimeMillis());
        JwtBuilder jwtBuilder = Jwts.builder().addClaims(claims)
                .signWith(SignatureAlgorithm.HS256, getKeyInstance(salt)).setSubject("orion").setIssuer("mitch");
        return jwtBuilder.compact();
    }

    public static Claims parseToken(String token, String salt){
        return Jwts.parser().setSigningKey(getKeyInstance(salt)).parseClaimsJws(token).getBody();
    }
}
